﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;

namespace KindleFireReader
{
    public partial class Form1 : Form
    {
        static public string Version = "1.0";
        public Form1()
        {
            InitializeComponent();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void locationOfKindleBooksToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path = "";
            DialogResult res = Form1.InputBox("Enter location", "Enter full path to Kindle books", ref path);
            RegistryKey regw = Registry.CurrentUser;
            try
            {
                regw = regw.CreateSubKey("Software\\KindleFireReader\\");
                
            }
            catch (Exception ex)
            {
                //Key was already created?
            }
            //regw.OpenSubKey(Registry.CurrentUser.ToString() + "\\Software\\KindleFireReader\\");
            regw.SetValue("location", path);
        }

        // http://www.csharp-examples.net/inputbox/
        private static DialogResult InputBox(string title, string promptText, ref string value)
        {
            Form form = new Form();
            Label label = new Label();
            TextBox textBox = new TextBox();
            Button buttonOk = new Button();
            Button buttonCancel = new Button();

            form.Text = title;
            label.Text = promptText;
            textBox.Text = value;

            buttonOk.Text = "OK";
            buttonCancel.Text = "Cancel";
            buttonOk.DialogResult = DialogResult.OK;
            buttonCancel.DialogResult = DialogResult.Cancel;

            label.SetBounds(9, 20, 372, 13);
            textBox.SetBounds(12, 36, 372, 20);
            buttonOk.SetBounds(228, 72, 75, 23);
            buttonCancel.SetBounds(309, 72, 75, 23);

            label.AutoSize = true;
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
            buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            form.ClientSize = new Size(396, 107);
            form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
            form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
            form.FormBorderStyle = FormBorderStyle.FixedDialog;
            form.StartPosition = FormStartPosition.CenterScreen;
            form.MinimizeBox = false;
            form.MaximizeBox = false;
            form.AcceptButton = buttonOk;
            form.CancelButton = buttonCancel;

            DialogResult dialogResult = form.ShowDialog();
            value = textBox.Text;
            return dialogResult;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            RegistryKey regr = Registry.CurrentUser;
            Object path;
            string[] sections;
            try
            {
                regr = regr.OpenSubKey("Software\\KindleFireReader");
                path = regr.GetValue("location");
                if (path == null)
                {
                    MessageBox.Show("You need to set the path in Options!", "KindleFireReader");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("You need to set the path in Options!", "KindleFireReader");
                return;
            }
            List<string> files = Directory.GetFiles(path.ToString(), "*.mbp").ToList();
            lstBooks.Items.Clear();
            lstNotes.Items.Clear();
            foreach (string file in files)
            {
                sections = file.Split('\\');
                lstBooks.Items.Add(sections[sections.Length - 1].Split('.')[0]);
            }
        }

        private void lstBooks_SelectedIndexChanged(object sender, EventArgs e)
        {
            lstNotes.Items.Clear();
            RegistryKey regr = Registry.CurrentUser;
            object path;
            int positiondata;
            int positionebar;
            StreamReader sr;
            string filestr;

            //Non printable
            char[] chrnull = { (char)0x00 };
            char[] chroe = { (char)0x0E };
            char[] chrff = { (char)0xFF };
            char[] chroi = { (char)0x01 };

            //printable
            string strapo = new string(new char[]{ (char)0x20, (char)0x19});

            List<string> highlights = new List<string>();
            string highlight;
            try
            {
                regr = regr.OpenSubKey("Software\\KindleFireReader");
                path = regr.GetValue("location");
                if (path == null)
                {
                    MessageBox.Show("You need to set the path in Options!", "KindleFireReader");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("You need to set the path in Options!", "KindleFireReader");
                return;
            }
            sr = new StreamReader(path.ToString() + "\\" + lstBooks.SelectedItem.ToString() + ".mbp");
            filestr = sr.ReadToEnd();
            sr.Close();

            //Cleaning up the riff
            filestr = filestr.Replace(new string(chrnull), "");
            filestr = filestr.Replace(new string(chroe), "");
            filestr = filestr.Replace(new string(chrff), "");
            filestr = filestr.Replace(new string(chroi), "");

            filestr = filestr.Replace(strapo, "\'");

            positiondata = filestr.IndexOf("DATA");

            while (positiondata != -1)
            {
                positionebar = filestr.IndexOf("EBAR", positiondata);
                highlight = filestr.Slice(positiondata + 4, positionebar);
                highlights.Add(highlight);
                positiondata = filestr.IndexOf("DATA", positiondata + 1);
            }

            if (highlights.Count > 0)
            {
                foreach (string high in highlights)
                {
                    lstNotes.Items.Add(high.Trim());
                }
            }
        }

        private void frmSaveNotes_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "Text Files *.txt|*.txt";
            saveFileDialog1.FileName = "notes.txt";
            if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
                return;

            StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
            sw.WriteLine(lstBooks.SelectedItem.ToString());
            foreach (string str in lstNotes.Items)
                sw.WriteLine(str);
            sw.Close();
        }

        private void fileok()
        {

        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Kindle Fire Reader\n" +
                            "By: Nathan Adams 2011\n" +
                            "Version: " + Form1.Version + "\n" +
                            "Purpose: Export highlights/notes from ebooks (stored in mpb files)\n" +
                            "Questions/comments can be directed to adamsna@datanethost.net", "KindleFireReader");
        }


    }
    //http://www.dotnetperls.com/string-slice
    public static class Extensions
    {
        /// <summary>
        /// Get the string slice between the two indexes.
        /// Inclusive for start index, exclusive for end index.
        /// </summary>
        public static string Slice(this string source, int start, int end)
        {
            if (end < 0) // Keep this for negative end support
            {
                end = source.Length + end;
            }
            int len = end - start;               // Calculate length
            return source.Substring(start, len); // Return Substring of length
        }
    }
}
